package cn.kgc.service.impl;

import cn.kgc.dao.AccountDao;
import cn.kgc.entity.Account;
import cn.kgc.service.AccountService;
import cn.kgc.utils.TransactionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

/**
 * @author Rock
 * @create 2020-08-25 9:58
 */
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private TransactionUtil transactionUtil;
    /**
     * 根据账号查询账户
     *
     * @param accountNum
     */
    public Account findAccountByNum(String accountNum) throws SQLException {
        return accountDao.getAccountByNum(accountNum);
    }

    /**
     * 更新账户
     *
     * @param account
     */
    public Integer modifyAccount(Account account) throws SQLException {
        return accountDao.updateAccount(account);
    }

    /**
     * 转账
     * @param sourceNum
     * @param desNum
     * @param money
     */
    public void transfer(String sourceNum, String desNum, Float money) throws SQLException {
        try{
            //开始事务
            transactionUtil.beginTransaction();
            //根据账号查询两个账户
            Account sourceAccount = accountDao.getAccountByNum(sourceNum);
            Account desAccount=accountDao.getAccountByNum(desNum);
            // 修改两个账户的余额
            sourceAccount.setAccountMoney(sourceAccount.getAccountMoney() - money);
            desAccount.setAccountMoney(desAccount.getAccountMoney() + money);
            //将数据持久化到数据库中
            accountDao.updateAccount(sourceAccount);
            //int i=1/0;
            accountDao.updateAccount(desAccount);
            //提交事务
            transactionUtil.commitTransaction();
            System.out.println("业务执行完毕");
        }catch(Exception e){
            e.printStackTrace();
            //回滚事务
            transactionUtil.rollbackTransaction();
            System.out.println("出错了，进行回滚");
        }finally {
            transactionUtil.closeTransaction();
        }
    }
}